<template>
  <div class="minio-container">
    <!-- 上传表单 -->
    <el-card class="upload-card">
      <template #header>
        <span>图片上传</span>
      </template>

      <el-form :model="uploadForm" label-width="80px">
        <el-form-item label="选择图片">
          <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="false"
              accept="image/*"
          >
            <el-button type="primary">选择图片</el-button>
          </el-upload>

          <!-- 图片预览 -->
          <div v-if="imagePreview" class="image-preview">
            <img :src="imagePreview" alt="预览图" class="preview-image" />
            <div class="file-info">已选择: {{ selectedFile?.name }}</div>
          </div>
        </el-form-item>

        <el-form-item label="图片备注">
          <el-input
              v-model="uploadForm.title"
              placeholder="请输入图片备注"
              maxlength="20"
              show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="uploadImage"
              :loading="uploading"
              :disabled="!selectedFile || !uploadForm.title.trim()"
          >
            上传图片
          </el-button>
          <el-button @click="clearForm">清空</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片列表 -->
    <el-card class="list-card">
      <template #header>
        <span>图片列表</span>
      </template>

      <el-row :gutter="20">
        <el-col
            v-for="item in imageList"
            :key="item.id"
            :span="6"
            class="image-item"
        >
          <el-card :body-style="{ padding: '0px' }">
            <img :src="item.path" class="image" />
            <div class="image-info">
              <p class="title">{{ item.title }}</p>
              <div class="actions">
                <el-button
                    type="danger"
                    size="small"
                    @click="deleteImage(item.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>

  <el-button type="primary" @click="navigateToPage">跳转到目标页</el-button>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

import { useRouter } from 'vue-router';

const router = useRouter();

const navigateToPage = () => {
  // 简单跳转
  router.push('/');
}

// 响应式数据
const uploadForm = ref({
  title: ''
})
const selectedFile = ref(null)
const imagePreview = ref('')
const imageList = ref([])
const uploading = ref(false)
const uploadRef = ref()

// 文件选择处理
const handleFileChange = (file) => {
  selectedFile.value = file.raw

  // 创建图片预览
  if (file.raw) {
    const reader = new FileReader()
    reader.onload = (e) => {
      imagePreview.value = e.target.result
    }
    reader.readAsDataURL(file.raw)
  }
}

// 清空表单
const clearForm = () => {
  uploadForm.value.title = ''
  selectedFile.value = null
  imagePreview.value = ''
  uploadRef.value.clearFiles()
}

// 上传图片
const uploadImage = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择图片')
    return
  }

  if (!uploadForm.value.title.trim()) {
    ElMessage.warning('请输入图片备注')
    return
  }

  uploading.value = true

  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('title', uploadForm.value.title)

    const response = await axios.post('/minio/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('上传成功')
      clearForm()
      fetchImageList()
    } else {
      ElMessage.error(response.data.errorMessage || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('接口不存在，请检查后端服务是否启动')
    } else {
      ElMessage.error('上传失败: ' + (error.response?.data?.errorMessage || error.message))
    }
  } finally {
    uploading.value = false
  }
}

// 获取图片列表
const fetchImageList = async () => {
  try {
    const response = await axios.get('/minio/list')
    if (response.data.code === 200) {
      imageList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取图片列表失败:', error)
    ElMessage.error('获取图片列表失败')
  }
}

// 删除图片
const deleteImage = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.delete(`/minio/delete/${id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchImageList()
    } else {
      ElMessage.error(response.data.errorMessage || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 页面加载时获取图片列表
onMounted(() => {
  fetchImageList()
})
</script>

<style scoped>
.minio-container {
  padding: 20px;
}

.upload-card {
  margin-bottom: 20px;
}

.image-preview {
  margin-top: 15px;
  text-align: center;
}

.preview-image {
  max-width: 200px;
  max-height: 200px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
}

.file-info {
  color: #666;
  font-size: 14px;
}

.image-item {
  margin-bottom: 20px;
}

.image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.image-info {
  padding: 14px;
}

.title {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #333;
}

.actions {
  text-align: right;
}
</style>